import random

from django import http
from django.views import View
from django_redis import get_redis_connection

from verifications.libs import constants
from verifications.libs.captcha.captcha import captcha
from verifications.response_code import RET
from verifications.yuntongxun.sms import CCP


class ImageCodeView(View):
    def get(self, request, image_code_id):
        name,text,image_data =captcha.generate_captcha()

        redis_conn = get_redis_connection("code")

        redis_conn.setex("img_code_%s" % image_code_id, 300, text)


        return http.HttpResponse(image_data, content_type="image/png")





class SmsCodeView(View):
    def get(self, request, mobile):
        image_code=request.GET.get("image_code")
        image_code_id=request.GET.get("image_code_id")

        if not all([image_code,image_code_id]):
            return http.JsonResponse({"code":4001,"errmsg":"参数不完整"})

        redis_conn=get_redis_connection("code")
        pipeline=redis_conn.pipeline()#开启管道(事务)
        redis_image_code=redis_conn.get("img_code_%s"%image_code_id)

        if not redis_image_code:
            return http.JsonResponse({"code":4001,"errmsg":"图片验证码过期"})

        pipeline.delete("img_code_%s"%image_code_id)

        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({"code":RET.DATAERR,"errmsg":"图片验证码错误"})

        send_flag = redis_conn.get("send_flag_%s" % mobile)

        if send_flag:
            return http.JsonResponse({"code": RET.DATAERR, "errmsg": "短信发送频繁"}, status=400)

        sms_code = "%06d"%random.randint(0,999999)
        print(sms_code)
        # ccp = CCP()
        # result = ccp.send_template_sms(mobile,[sms_code,5],1)
        #
        # if result == -1:
        #     return http.JsonResponse({"code":4001,"errmsg":"短信发送失败"})
        #
        # redis_conn.setex("sms_code_%s"%mobile,300,sms_code)
        #
        # return http.JsonResponse({"code":"0","errmsg":"ok"})
        #使用celery发送短信
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code,constants.REDIS_SMS_CODE_EXPIRES/60)

        # import time
        # time.sleep(10)

        pipeline.setex("sms_code_%s"%mobile,constants.REDIS_SMS_CODE_EXPIRES,sms_code)

        pipeline.setex("send_flag_%s"%mobile,60,1)


        pipeline.execute()#提交管道(事务)

        return http.JsonResponse({"code":RET.OK,"errmsg":"ok"})






